package com.api_gateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Objects;
// 限流过滤器
@Component
public class RateLimitFilter implements WebFilter {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String ip = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress();
        String key = "rate_limit:" + ip;

        // 使用Redis实现滑动窗口计数
        Long current = redisTemplate.opsForValue().increment(key);
        if (current == null) {
            current = 0L;
        }
        if (current == 1) {
            // 如果是第一次访问，设置key的过期时间
            redisTemplate.expire(key, Duration.ofMinutes(1));
        }
        if (current > 100) { // 限制1分钟内同一IP最多100次请求
            // 超出限制，返回429 Too Many Requests
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            String result = "{\"code\": 429, \"msg\": \"Too Many Requests\"}";
            return exchange.getResponse().writeWith(
                Mono.just(exchange.getResponse().bufferFactory().wrap(result.getBytes()))
            );
        }
        return chain.filter(exchange);
    }
}
